const listener = new Listener();
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
	listener.onMessage(message, sender, sendResponse);
});

require(["vue", "scroll", "alert", "tip", "showdown"], (Vue, scroll, alert, tip, showdown) => {
	let warn = alert(alert.theme.default());
	let app = new Vue({
		el: "#app",
		data: {
			id: "",
			username: "",
			password: "",
			passwordRepeat: "",
			access_token: "",
			updateTime: "",
			autoSync: false,
			autoUpload: false,
			autoDownload: false,
			interval: 0,
			from: "",
			// 路由栈
			routerStack: [],
			status: false,
			// 用户是否已注册
			isRegist: false,
			encrypted: "",
			logining: false,
			first: false,
			noticeList: [],
			noticeRead: {},
			targetNotice: {},
			converter : new showdown.Converter(), 
		},
		methods: {
			// 账号密码登录
			login() {
				if (this.logining) return;
				if (this.username == "") {
					return warn.msg(tip.NO_NAME);
				}
				if (this.password == "") {
					return warn.msg(tip.NO_PWD);
				}
				warn.msg(tip.LOGIN_AFTER_CLEAR, {
					title: "友情提示",
				}, (result) => {
					if (!result) {
						return;
					}
					if (this.username.length < 3 || this.password.length < 6 || this.password.length > 12) {
						return warn.msg(tip.PWD_ERROR);
					}
					this.logining = true;
					chrome.runtime.sendMessage({
						username: this.username,
						password: this.password,
						type: "login",
					});
				});
			},
			// 用户注册
			regist() {
				if (this.username == "") {
					return warn.msg(tip.NO_NAME);
				}
				if (this.username.length < 3) {
					return warn.msg(tip.NAME_LEN);
				}
				if (this.password == "") {
					return warn.msg(tip.NO_PWD)
				}
				if (this.password.length < 6 || this.password.length > 12) {
					return warn.msg(tip.PASSWORD_LEN);
				}
				if (this.password != this.passwordRepeat) {
					return warn.msg(tip.REPEAT);
				}
				warn.msg(tip.REGIST_REMBER, (result) => {
					if (result) {
						app.loginIng = true;
						chrome.runtime.sendMessage({
							type: "regist",
							username: this.username,
							password: this.password
						});
					}
				});
			},
			// token登录
			createSync() {
				if (this.logining || this.access_token == "") {
					return;
				}
				let create = (result) => {
					if (result) {
						app.logining = true;
						chrome.runtime.sendMessage({
							id: this.id,
							type: "createSync",
							access_token: this.access_token
						});
					}
				}
				if (this.id == "") {
					warn.msg(tip.NO_ID, create);
				}
				else {
					warn.msg(tip.LOGIN_AFTER_CLEAR, {
						title: "友情提示",
					}, create);
				}
			},
			// 上传本地书签
			upload() {
				chrome.runtime.sendMessage({ type: "upload" });
			},
			// 同步云端书签
			download() {
				chrome.runtime.sendMessage({ type: "download" });
			},
			// 返回上一层(页面路由回退)
			back() {
				if (this.routerStack.length > 1) {
					this.routerStack.pop();
				}
			},
			// 前进一层(页面路由入栈)
			enter(router) {
				this.routerStack.push(router);
			},
			setting(key) {
				this[key] = !this[key];
				chrome.runtime.sendMessage({
					type: "setting",
					key: key,
					value: this[key],
				});
			},
			readNotice(notice) {
				this.noticeRead[notice.id] = true;
				chrome.runtime.sendMessage({ type: "noticeRead", id: notice.id });
				this.targetNotice = notice;
				this.enter('notice');
			},
			submitTimer() {
				chrome.runtime.sendMessage({
					type: "setTimer",
					interval: this.interval
				}, () => {
					this.back();
				});
			},
			clear() {
				warn.msg(tip.CLEAR, (result) => {
					if (result) {
						chrome.runtime.sendMessage({ type: "clear" });
					}
				});
			},
			revert() {
				warn.msg(tip.REVERT, (result) => {
					if (result) {
						chrome.runtime.sendMessage({ type: "revert" });
					}
				});
			},
			help() {
				chrome.tabs.create({ url: "https://lyxfj.gitee.io/bookmarkssync/" });
			},
			format: Lyx.format
		},
		computed: {
			router() {
				let router = this.routerStack[this.routerStack.length - 1];
				if (["pay", "notice"].indexOf(router) < 0 && this.routerStack.length != 0) {
					chrome.runtime.sendMessage({
						type: "routerStack",
						routerStack: this.routerStack
					});
				}
				return router;
			},
			unreadNotic() {
				return this.noticeList.filter((item) => {
					return !this.noticeRead[item.id];
				}).length;
			},
			title() {
				let router = this.routerStack[this.routerStack.length - 1];
				return {
					setting: "设置",
					accountLogin: "登录",
					regist: "注册",
					pay: "付费",
					tokenLogin: "私人令牌登录",
					setTimer: "设置自动同步时间间隔",
					noticeList: "系统通知",
					notice: "通知详情",
				}[router];
			},
			autoSyncStyle() {
				if (this.autoSync) {
					return {
						background: "#8bc34a",
						left: "26px",
					}
				}
				else {
					return {
						background: "#eee",
						left: "1px",
					}
				}
			},
			autoUploadStyle() {
				if (this.autoUpload) {
					return {
						background: "#8bc34a",
						left: "26px",
					}
				}
				else {
					return {
						background: "#eee",
						left: "1px",
					}
				}
			},
			autoDownloadStyle() {
				if (this.autoDownload) {
					return {
						background: "#8bc34a",
						left: "26px",
					}
				}
				else {
					return {
						background: "#eee",
						left: "1px",
					}
				}
			}
		}
	});

	let scrollStyle = {
		height: 320,
		width: 360,
		yBarBack: {
			background: "rgba(0,0,0,0)"
		},
		yBar: {
			background: "rgba(0,0,0,0.1)"
		},
		mouseover: true,
		yMouseover: true,
		yBarSwitch: true,
		dragSwitch: false
	};

	scroll("#setting", scrollStyle);
	scroll("#pay", scrollStyle);
	scroll("#noticeList", scrollStyle);
	
	function update(callback) {
		// 获取缓存信息
		chrome.runtime.sendMessage({ type: "getLocalGist" }, (message) => {
			delete message.type;
			for (let key in message) {
				if (key == "routerStack") {
					message[key].forEach((item) => {
						app[key].push(item);
					});
					continue;
				}
				app[key] = message[key];
			}

			// 通知
			chrome.runtime.sendMessage({ type: "notice" });

			if (app.first) {
				warn.msg(tip.HELP, {
					title: "Hello！",
					button: { ok: "使用帮助" },
				}, (result) => {
					if (!result) {
						return;
					}
					chrome.tabs.create({ url: "https://lyxfj.gitee.io/bookmarkssync/" });
					chrome.runtime.sendMessage({
						type: "setting",
						key: "first",
						value: false,
					});
				});
			}

			if (callback) {
				callback();
			}
		});
	}

	listener.setHandle("getInfo", (message) => {
		delete message.type;
		for (let key in message) {
			app[key] = message[key];
		}
	});

	listener.setHandle("createSyncResult", (message) => {
		app.logining = false;
		if (message.result) {
			update(() => {
				app.enter("setting");
			});
		}
		else {
			warn.msg(tip.TOKEN_ERROR);
		}
	});

	listener.setHandle("loginResult", (message) => {
		app.logining = false;
		if (message.result) {
			app.enter("setting");
		}
		else {
			warn.msg(message.message);
		}
	});

	listener.setHandle("message", (message) => {
		warn.msg(message.message);
	});

	listener.setHandle("registResult", (message) => {
		app.encrypted = message.encrypted;
		app.enter(message.router);
	});

	listener.setHandle("noticeResult", (message) => {
		while (app.noticeList.length != 0) {
			app.noticeList.pop();
		}
		message.noticeList.sort((a, b) => {
			return a.createTime > b.createTime ? 1 : -1;
		}).forEach((item) => app.noticeList.push(item));
		app.noticeList.filter((item) => {
			return item.level == 1 && !app.noticeRead[item.id];
		}).forEach((item) => {
			item.title == item.title || "系统通知";
			warn.msg(item.content, item, (result) => {
				if (result) {
					app.noticeRead[item.id] = true;
					chrome.runtime.sendMessage({ type: "noticeRead", id: item.id });
				}
			});
		});
	});

	update();
});
